$(function(){
    cssBind();
});

var publicDom = {

    //配置项
    config:{
        rootUrl: "http://xiaogong.ftp29.scauidc.com",
        url: "http://172.20.10.6:8080/onlineRetailer", // 请求接口的url
        imgurl:"http://og07ks0jb.bkt.clouddn.com/",
        //图片路径
        //url: "http://localhost:8080/wxCrowd",
        userType: 'usertype', // 2为普通用户
        storageId: "uid", // 本地storage的item的名字
    },

    // temp:{
    // 	searchType:0,
    // },

    getData: function(type, url, param, f, isAsync, err) {
        if(localStorage.getItem(publicDom.config.storageName)){
            param.tokennum=localStorage.getItem(publicDom.config.storageName);
        }
        var ajaxParam  = {
            type: type,
            url: url,
            data: param,
            async: isAsync !== false,
            success: function(data) {
                var jsonData;
                try{
                    jsonData = $.parseJSON(data);
                }catch(e) { // 返回值不是json格式
                    if(typeof f !== 'function') { // 如果没有回调函数,抛出异常。
                        throw new Error('请求数据之后，没有回调函数!');
                    }
                    f(data);
                    return;
                }
                if(jsonData.code === 302){
                    window.location.href = jsonData.msg||"../html/login_store.html";

                } else if(jsonData.code===-1){
                    //超时或者存在
                    window.localStorage.removeItem(publicDom.config.userType);
                    window.localStorage.removeItem(publicDom.config.storageName);
                    window.location.href = jsonData.msg||"../html/login_store.html";
                }
                else {

                    if(typeof f !== 'function') { // 如果没有回调函数,抛出异常。

                        throw new Error('请求数据之后，没有回调函数!');
                    }
                    f(jsonData);
                }
            },
        };
        $.ajax(ajaxParam);
    },

    getDataNoToken: function(type, url, param, f, isAsync, err) {

        var ajaxParam  = {
            type: type,
            url: url,
            data: param,
            async: isAsync !== false,
            success: function(data) {
                var jsonData;
                try{
                    jsonData = $.parseJSON(data);
                }catch(e) { // 返回值不是json格式
                    if(typeof f !== 'function') { // 如果没有回调函数,抛出异常。
                        throw new Error('请求数据之后，没有回调函数!');
                    }
                    f(data);
                    return;
                }
                if(jsonData.code === 302){
                    window.location.href = jsonData.msg||"../html/login_store.html";

                } else if(jsonData.code===-1){
                    //超时或者存在
                    window.localStorage.removeItem(publicDom.config.userType);
                    window.localStorage.removeItem(publicDom.config.storageName);
                    window.location.href = jsonData.msg||"../html/login_store.html";
                }
                else {

                    if(typeof f !== 'function') { // 如果没有回调函数,抛出异常。

                        throw new Error('请求数据之后，没有回调函数!');
                    }
                    f(jsonData);
                }
            },
        };
        $.ajax(ajaxParam);
    },



    initMenu:function(activeFlag){
        var newUrl = publicDom.config.url + '/menu/findmenu',
            param = {
                token : localStorage.getItem(publicDom.config.storageName)||''
            };
        publicDom.getData("post", newUrl, param, function(json) {
            $('#menu').empty();
            if(json.code===200){
                var $ulDom=$('<ul></ul>');
                for (var i=0;i<json.data.length;i++) {
                    var  listr='<li><a href="'+json.data[i].url+'">'+json.data[i].name+'</a></li>';
                    $ulDom.append(listr);
                }
                $('#menu').append($ulDom);
            }
        });
    },

    resetPwd:function(){
        var account = localStorage.getItem(publicDom.config.storageId);
        $('#changePw').on('click',function(){
            $('#user_account').val(account);
            $('#resetPd').modal('show');
        });

        $('#change').on('click',function(){
            var userType = localStorage.getItem(publicDom.config.userType);
            if ($('#newPw').val()!=$('#repeatPw').val()) {
                alert('两次输入的密码不一致！');
                return false;
            }

            if (userType == 1) {
                var url = publicDom.config.url + '/adminUser/resetPwd';
            }else if (userType == 2){
                var url = publicDom.config.url + '/store/resetPwd';
            }
            param = {
                account : $('#user_account').val(),
                oldPw : $.md5( $('#oldPw').val()),
                newPw : $.md5( $('#newPw').val())
            };
            publicDom.getData('post',url,param,function(data){
                if (data.code == 200) {
                    alert('修改成功,请重新登录！');
                    if (userType == 2) {
                        window.location.href = "../html/login_store.html";
                    }else if (userType == 1) {
                        window.location.href = "../html/login.html";
                    }
                }else{
                    alert('修改失败！');
                }
            });
        });
    },
    showConfirmModal:function(info,status,msgBody){
        var gobalModal = "";
        $("#confirm").remove();
        var font_icon = '';
        if(info == '成功'){
            font_icon = 'glyphicon glyphicon-ok';
        }else if(info == '警告'){
            font_icon = 'glyphicon glyphicon-warning-sign';
        }
        else{
            font_icon = 'glyphicon glyphicon-remove';
        }


        if(status!="default"&&status!="delete"){
            gobalModal = '<button type="button" id="confirmBtn" class="btn btn-default comFirmModal hide" data-toggle = "modal" data-target = "#confirm">确定</button>'+
                '<div class = "modal fade" id = "confirm" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true">'+
                '<div class = "modal-dialog">'+
                '<div class = "modal-content">'+
                '<div class = "modal-header">'+
                '<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">&times;</button>'+
                '<h4 class = "modal-title text-danger" id = "myModalLabel">&nps<span class="'+ font_icon +'"></span> '+info+'</h4>'+
                '</div>'+
                '<div class = "modal-body">'+msgBody+'</div>'+
                '<div class = "modal-footer">'+
                '<button type = "button" class = "btn btn-danger confirm" data-dismiss = "modal">确定</button>'+
                '</div>'+
                '</div>'+
                '</div>'+
                '</div>';
        }
        else if(status=="delete"){
            gobalModal = '<button type="button" id="confirmBtn" class="btn btn-default comFirmModal hide" data-toggle = "modal" data-target = "#confirm">确定</button>'+
                '<div class = "modal fade" id = "confirm" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true">'+
                '<div class = "modal-dialog">'+
                '<div class = "modal-content">'+
                '<div class = "modal-header">'+
                '<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">&times;</button>'+
                '<h4 class = "modal-title text-primary" id = "myModalLabel"><span class="'+ font_icon +'"></span> '+info+'</h4>'+
                '</div>'+
                '<div class = "modal-body">'+msgBody+'<span class="text-danger font-d-under font-w-bold"></span></div>'+
                '<div class = "modal-footer">'+
                '<button type = "button" class = "btn btn-primary deleteConfirm" data-dismiss = "modal">确定</button>'+
                '<button type = "button" class = "btn btn-default confirm" data-dismiss = "modal">取消</button>'+
                '</div>'+
                '</div>'+
                '</div>'+
                '</div>';
        }
        else{
            gobalModal = '<button type="button" id="confirmBtn" class="btn btn-default comFirmModal hide" data-toggle = "modal" data-target = "#confirm">确定</button>'+
                '<div class = "modal fade" id = "confirm" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true">'+
                '<div class = "modal-dialog">'+
                '<div class = "modal-content">'+
                '<div class = "modal-header">'+
                '<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">&times;</button>'+
                '<h4 class = "modal-title text-primary" id = "myModalLabel"><span class="'+ font_icon +'"></span> '+info+'</h4>'+
                '</div>'+
                '<div class = "modal-body">'+msgBody+'</div>'+
                '<div class = "modal-footer">'+
                '<button type = "button" class = "btn btn-primary confirm" data-dismiss = "modal">确定</button>'+
                '</div>'+
                '</div>'+
                '</div>'+
                '</div>';
        }
        $("body").append(gobalModal);
        $("#confirmBtn").trigger('click');
    },


    GetRequest:function(){

        var url = location.search; //获取url中"?"符后的字串

        var theRequest = new Object();

        if (url.indexOf("?") != -1) {

            var str = url.substr(1);

            strs = str.split("&");

            for(var i = 0; i < strs.length; i ++) {

                theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);

            }

        }

        return theRequest;

    }

};

var cssBind = function() {
    searchCss();
    loginCss();
    signOut();
    searchTo();
}


var searchCss = function() {


    $("#search1 .seach-in span").click(function() {
        if($(this).find('ul').is(':visible')){
            $(this).find('ul').slideUp('fast');
        }else{
            $(this).find('ul').slideDown('fast');
        }
    });
    $("#index-seachin span").click(function() {
        if($(this).find('ul').is(':visible')){
            $(this).find('ul').slideUp('fast');
        }else{
            $(this).find('ul').slideDown('fast');
        }
    });
    $("#search1 .seach-in span ul li").click(function() {
        var text = $(this).text();
        // if(text=="一口价"){
        // 	publicDom.temp.searchType = 1;
        // }else if (text=="拍卖") {
        // 	publicDom.temp.searchType = 2;
        // }else{
        // 	publicDom.temp.searchType = 0;
        // }
        $(this).parent().parent().find('b').text(text);
    });
    $("#index-seachin span ul li").click(function() {
        var text = $(this).text();
        // if(text=="一口价"){
        // 	publicDom.temp.searchType = 1;
        // }else if (text=="拍卖") {
        // 	publicDom.temp.searchType = 2;
        // }else{
        // 	publicDom.temp.searchType = 0;
        // }
        $(this).parent().parent().find('b').text(text);
    });
}

var loginCss = function() {
    if(localStorage.getItem(publicDom.config.storageId)){
        $('#infofont').show();//显示用户名
        $('#infofonts').hide();//隐藏请登录
        $('#infofonthead').text(localStorage.getItem("uid"));
    }else{
        $('#infofonts').show();
        $('#infofont').hide();
    }
}

var signOut = function() {
    $('.log-out').click(function(event) {
        window.localStorage.removeItem(publicDom.config.storageName);
        window.location.href = "login.html";
    });
}


var searchTo  = function () {
    $("#search1 .seach-in > a").click(function() {
        var str = $('#search1 .seach-in span b').text();
        var type = 0;
        if(str=="一口价"){
            type = 1;
        }else if(str == "拍卖"){
            type = 2;
        }else {
            type = 0;
        }
        var filter = $("#search1 .seach-in input").val();
        window.location = "listItem.html?type="+type+"&filterStr=" + escape(filter);
    });
    $("#index-seachin > a").click(function() {
        var str = $('#index-seachin span b').text();
        var type = 0;
        if(str=="一口价"){
            type = 1;
        }else if(str == "拍卖"){
            type = 2;
        }else {
            type = 0;
        }
        var filter = $("#index-seachin input").val();
        window.location = "listItem.html?type="+type+"&filterStr=" + escape(filter);
    });
}